package org.hroze.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Cmd {
	public static final String encoding="GBK";
	public static void exit(){
		Runtime.getRuntime().exit(0);
	}
	/**
	 * 执行命令
	 * @param cmd
	 * @return
	 */
	public static CmdResult exec(String cmd){
		return exec(cmd,encoding);
	}
	/**
	 * 执行指定命令，返回指定编码的字符串
	 * @param cmd
	 * @param encoding
	 * @return
	 */
	public static CmdResult exec(String cmd,String encoding){
		CmdResult res=new CmdResult();
		try {
			Process p = Runtime.getRuntime().exec(cmd);
			res.setResponse(getStr(p,encoding));
			res.setExitValue(p.exitValue());
			p.destroy();
		} catch (Exception  e) {
			e.printStackTrace();
			res.setError(e.getMessage());
		}
		if(res.getResponse()==null){
			res.setResponse("\" \"");
		}
		return res;
	}
	private static String getStr(Process p,String encoding) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(p
				.getInputStream(),"GBK"));
		StringBuffer sb = new StringBuffer();
		String inline;
		while (null != (inline = br.readLine())) {
			sb.append(inline).append("\n");
		}
		return sb.toString();
	}
	public static void main(String[] args) throws IOException {
		String command = "ping baidu.com";// 系统命令哦
		CmdResult r=exec(command);
		System.out.print(r.getResponse());
		System.out.println(r.getExitValue());
	}
}
